package com.kob.botrunningsysytem.service.impl.utils;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BotPool extends Thread{
    private final ReentrantLock lock=new ReentrantLock();
    private final Queue<Bot> bots=new LinkedList<>();
    private final Condition condition= lock.newCondition();


    public void addBot(Integer userId,String botCode,String input){
        lock.lock();
        try {
            bots.add(new Bot(userId,botCode,input));
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    void consume(Bot bot){
        Consumer consumer=new Consumer();//来一个botcode执行，启动一个线程
        consumer.startTimeout(2000,bot);
    }
    @Override
    public void run(){
        while(true){
            lock.lock();
            if(bots.isEmpty()){
                try {
                    condition.await();
                }catch (InterruptedException e){
                    e.printStackTrace();
                    lock.unlock();
                    break;
                }
            }else{
                Bot bot=bots.remove();
                lock.unlock();
//                拿去执行代码
                consume(bot);
            }
        }
    }
}
